$().ready(function () {
    $('.delete').click(function () {
        return confirm('Are you sure?');
    });

    $('.datepicker').datepicker();
});


function initTree(options) {
    $("#tree").jstree({ "plugins":["themes", "html_data", "ui", "crrm", "dnd", "contextmenu"],
        "contextmenu":{
            'items':{
                "ccp":{
                    // The item label
                    "label":"Edit",
                    // The function to execute upon a click
                    "action":function (obj) {
                        location.href = options.edit + $(obj).attr('id');
                    },
                    // All below are optional
                    "_disabled":false, // clicking the item won't do a thing
                    "_class":"class", // class is applied to the item LI node
                    "separator_before":false, // Insert a separator before the item
                    "separator_after":true, // Insert a separator after the item
                    // false or string - if does not contain `/` - used as classname
                    "icon":false,
                    "submenu":false
                },
                "create":{
                    // The item label
                    "label":"Create",
                    // The function to execute upon a click
                    "action":function (obj) {
                        location.href = options.add + '/parent/' + $(obj).attr('id');
                    },
                    // All below are optional
                    "_disabled":false, // clicking the item won't do a thing
                    "_class":"class", // class is applied to the item LI node
                    "separator_before":false, // Insert a separator before the item
                    "separator_after":true, // Insert a separator after the item
                    // false or string - if does not contain `/` - used as classname
                    "icon":false
                }
            }
        },
        "dnd":{
            'drop_finish':function () {
                console.log('drop finished');
            },

            'drag_check':function (data) {
                return true;
            },

            'drag_finish':function (data) {
                console.log('Drag finished');
            }
        }
    })
//        .bind("select_node.jstree", function (event, data) {
//            var id = data.rslt.obj.attr("id");
//            location.href = '/pages/edit/id/' + id;
//        })
        .delegate("a", "click", function (event, data) {
            event.preventDefault();
        })
        .bind("move_node.jstree", function (e, data) {
            data.rslt.o.each(function (i) {
                $.ajax({
                    async:false,
                    type:'POST',
                    url:options.dnd,
                    data:{
                        "operation":"move_node",
                        "id":$(this).attr("id").replace("node_", ""),
                        "ref":data.rslt.cr === -1 ? 0 : data.rslt.np.attr("id").replace("node_", ""),
                        "position":data.rslt.cp + i,
                        "title":data.rslt.name,
                        "copy":data.rslt.cy ? 1 : 0
                    },
                    success:function (r) {
                        if (!r.status) {
                            $.jstree.rollback(data.rlbk);
                        }
                        else {
                            $(data.rslt.oc).attr("id", "node_" + r.id);
                            if (data.rslt.cy && $(data.rslt.oc).children("UL").length) {
                                data.inst.refresh(data.inst._get_parent(data.rslt.oc));
                            }
                        }
                        $("#analyze").click();
                    }
                });
            });
        })
        .bind("rename.jstree", function (e, data) {
            $.post(
                options.dnd,
                {
                    "operation":"rename_node",
                    "id":data.rslt.obj.attr("id").replace("node_", ""),
                    "title":data.rslt.new_name
                },
                function (r) {
                    if (!r.status) {
                        $.jstree.rollback(data.rlbk);
                    }
                }
            );
        })
        .bind("remove.jstree", function (e, data) {
            data.rslt.obj.each(function () {
                $.ajax({
                    async:false,
                    type:'POST',
                    url:options.dnd,
                    data:{
                        operation:"remove_node",
                        id:this.id.replace("node_", "")
                    },
                    success:function (r) {
                        if (!r.status) {
                            data.inst.refresh();
                        }
                    }
                })
            })
        });

    $("#tree-control input").click(function () {
        if (this.id == 'create') {
            location.pathname = options.add;
        } else {
            $("#tree").jstree(this.id);
        }
    });
}

function post(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }
    }

    document.body.appendChild(form);
    form.submit();
}

function initAddAnswerButton() {

    $('#add_new_answer').live('click', function() {
        var i = $('.poll_input').length;

        var id = 'answer_'+i;
        var line_id = 'line_'+i;
        var input = "<input id="+id+" class='poll_input' name='new_answer[]'> </input>";
        var del = "<input class='del_answer' type='button' value='Del' />";
        var line = "<div id="+line_id+"><span>"+(++i)+".</span>"+input+del+"</div>";
        $("#add_new_answer").before(line);

    });
}

function initDelAnswerButton() {
    $('.del_answer').live('click', function() {
        $(this).parent().remove();

    });
}